package earogya.ehr.patient_details.messages;

import java.io.IOException;
import org.hibernate.HibernateException;
import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.DataTypeException;
import ca.uhn.hl7v2.model.v251.message.ADT_A60;
import ca.uhn.hl7v2.model.v251.segment.IAM;
import earogya.ehr.patient_details.HibernateManager;
import earogya.ehr.patient_details.PatientAllergy;


/***
 * 
 * @author Ureka
 *
 * ADT A60 message is used to update the patient's allergy details
 */
public class ADT_A60_Handler {
	private ADT_A60 adtMsg;
	private PatientAllergy pAllergy;
	HibernateManager hibernateManager=new HibernateManager();
	public ADT_A60_Handler(ADT_A60 adtMsg){
		this.adtMsg=adtMsg;
	}
	
	
	/**
	 * 
	 * Identify separate segments in the message and add the details in the
	 * segments to their respective POJO classes
	 * 
	 * @return
	 * @throws HL7Exception
	 * @throws IOException
	 */
	public String manageMessage() throws HL7Exception, IOException{
		String ack=null;
		try{
		this.updateAllergyDetails();
		ack=adtMsg.generateACK().encode();
		} catch (HibernateException e) {
			HL7Exception ex = new HL7Exception("Could not save to Database");
			ack = adtMsg.generateACK("AE", ex).encode();
		} catch (IOException e) {
			HL7Exception ex = new HL7Exception("An IO error ocuured");
			ack = adtMsg.generateACK("AE", ex).encode();
		} catch(DataTypeException e){
			HL7Exception ex = new HL7Exception("An error occured while data type conversion");
			ack = adtMsg.generateACK("AE", ex).encode();
		}catch (HL7Exception e) {
			HL7Exception ex = new HL7Exception("Could not parse the message");
			ack = adtMsg.generateACK("AE", ex).encode();
		}catch(Exception e){
			HL7Exception ex = new HL7Exception("An error occured");
			ack = adtMsg.generateACK("AE", ex).encode();
		}
		return ack;
	}
	
	
	/**
	 * 
	 * Save the patient's allergy details to the databse
	 * 
	 * @throws NumberFormatException
	 * @throws HL7Exception
	 * @throws IOException
	 * @throws HibernateException
	 * @throws DataTypeException
	 */
	private void updateAllergyDetails() throws NumberFormatException, HL7Exception, IOException, HibernateException, DataTypeException{
		IAM iam;
		for(int i=0;i<adtMsg.getIAMReps();i++){
			iam=adtMsg.getIAM(i);
			pAllergy=new PatientAllergy();
			pAllergy.setPatientId(Integer.parseInt(adtMsg.getPID().getPatientID().getIDNumber().getValue()));
			pAllergy.setAllergyCode(iam.getAllergenCodeMnemonicDescription().getComponent(0).toString());
			pAllergy.setSeverity(iam.getAllergySeverityCode().getComponent(0).toString());
			hibernateManager.saveObject(pAllergy);
		}
	}
	
}
